package com.example.uniappspringbootstartweb.controller;

import com.example.uniappspringbootstartweb.DTO.UserActivityDTO;
import com.example.uniappspringbootstartweb.Util.ShuffleUtil;
import com.example.uniappspringbootstartweb.entity.Comments;
import com.example.uniappspringbootstartweb.entity.User;
import com.example.uniappspringbootstartweb.entity.Userlike;

import com.example.uniappspringbootstartweb.entity.Publish;
import com.example.uniappspringbootstartweb.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author DELL
 */
@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private UserlikeService userlikeService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private PublishService publishService;

    @Autowired
    private UserService userService;

    @GetMapping("/random-four-activities")
    public ResponseEntity<List<UserActivityDTO>> getRandomFourActivities(@RequestParam Integer contentId) {
        List<UserActivityDTO> activities = new ArrayList<>();

        // 获取所有记录并封装到DTO中
        addActivitiesToDTO(activities, userlikeService::getlikeByContentid, contentId, 1);
        addActivitiesToDTO(activities, commentService::getCommentByContentid, contentId, 2);
        addActivitiesToDTO(activities, publishService::getPublishByContentid, contentId, 3);

        // 如果有至少12条记录，则打乱顺序并随机选择4条
        if (activities.size() >= 12) {
            // 只取前12条记录进行打乱
            List<UserActivityDTO> topTwelve = activities.stream().limit(12).collect(Collectors.toList());
            activities = ShuffleUtil.shuffleList(topTwelve);
            activities = activities.stream().limit(12).collect(Collectors.toList());
        } else {
            // 如果少于12条记录，直接打乱现有记录
            activities = ShuffleUtil.shuffleList(activities);
            // 如果活动数量大于4条，限制为4条
            if (activities.size() > 4) {
                activities = activities.stream().limit(4).collect(Collectors.toList());
            }
        }
        return ResponseEntity.ok(activities);
    }

    private <T> void addActivitiesToDTO(List<UserActivityDTO> activities, Function<Long, List<T>> serviceMethod, Integer contentId, Integer activityType) {
        List<T> allRecords = serviceMethod.apply(Long.valueOf(contentId));
        if (allRecords.size() <= 4) {
            processRecords(allRecords, activityType, activities);
        } else {
            allRecords.stream()
                    .skip(Math.max(0, allRecords.size() - 4))
                    .forEach(record -> processRecord(record, activityType, activities));
        }
    }

    private <T> void processRecords(List<T> records, Integer activityType, List<UserActivityDTO> activities) {
        for (T record : records) {
            processRecord(record, activityType, activities);
        }
    }

    private <T> void processRecord(T record, Integer activityType, List<UserActivityDTO> activities) {
        Long userId = extractUserIdFromRecord(record);
        User user = userService.findById(userId);

        UserActivityDTO dto = new UserActivityDTO();
        dto.setImg(user.getImg());
        dto.setNichen(user.getNichen());
        dto.setActivityType(activityType);
        // 根据不同类型设置具体的activityContent
        if (record instanceof Userlike userlike) {
            dto.setActivityContent("Liked: " + userlike.toString()); // 假设你需要将对象转换为字符串或其他形式
        } else if (record instanceof Comments comment) {
            dto.setActivityContent(comment.getMessage()); // 如果评论有getContent方法
        } else if (record instanceof Publish publish) {
            dto.setActivityContent("Published: " + publish.toString()); // 如果发布有getContent方法
        }
        activities.add(dto);
    }

    private Long extractUserIdFromRecord(Object record) {
        if (record instanceof Userlike userlike) {
            return userlike.getUserid();
        } else if (record instanceof Comments comment) {
            return comment.getUserid();
        } else if (record instanceof Publish publish) {
            return publish.getUserid();
        } else {
            throw new IllegalArgumentException("Unknown record type: " + record.getClass().getName());
        }
    }
}